<template>
    <div style="height: 155px">
        <div style="position: absolute">
            <el-upload
                :file-list="fileList"
                :before-upload="beforeAvatarUpload"
                :class="{disabled:uploadDisabled}"
                :on-preview="handlePictureCardPreview"
                :on-progress="handleProgress"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :data="{code:this.hotelUuCode}"
                :action="serviceUrl"
                list-type="picture-card"
                accept=".mp4"
                :on-change="AvatarAUDIO"
                :headers="header"
            >
                <i style="vertical-align: middle;z-index:1;" class="el-icon-plus"></i>
            </el-upload>
        </div>
        <div style="position: relative;z-index: 999;" v-if="videoFlag == true">
            <el-progress  type="circle" :percentage="eventUploadPercent"
                          style="vertical-align: middle;position: absolute;margin-left: 0.7%;margin-top: 12px;"></el-progress>
        </div>
        <el-dialog :visible.sync="dialogVisible">
            <video
                width="100%"
                :src="dialogImageUrl"
                controls
            />
        </el-dialog>
    </div>
</template>

<script>
    import {
        getToken
    } from '@/utils/auth'
    import request from '@/utils/request'
    import {Message} from 'element-ui'

    export default {
        name: 'VideoUpload',
        props: {
            uploadUrl: {
                type: String,
                default: ''
            },
            hotelUuCode: {
                type: String,
                default: ''
            },
            serviceFileList: {
                type: Array,
                default: []
            },
            removeUrl: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                serviceUrl: this.uploadUrl,
                fileList: this.serviceFileList,
                filename: '',
                uploadDisabled: false,
                dialogImageUrl: '',
                dialogVisible: false,
                header: {'X-Token': getToken(), fileType: 3},
                type: 1,
                videoFlag:false,
                eventUploadPercent:0
            }
        },
        watch: {
            filename: function () {
                this.$emit('videocode', this.filename)
            },
            fileList: function () {
                if (this.fileList.length > 0) {
                    this.filename = this.fileList[0]['url']
                    this.uploadDisabled = true
                    this.$nextTick(function () {
                        this.changeImgTag()
                    })

                }
            }
        },
        methods: {
            AvatarAUDIO(file, fileList) {
                if (file.response && file.response.code == 0 && file.response.succ) {
                    this.eventUploadPercent=100
                    window.setTimeout(() => {
                        this.videoFlag = false;
                        file.url = '/static/img/upLoad.jpg'
                        this.type = 2
                    }, 300)

                }
            },
            handleRemove(file, fileList) {
                if (file && file.status === 'success') {
                    this.uploadDisabled = false
                    this.filename = ''
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                if (this.type == 2) {
                    this.dialogImageUrl = file.response.url
                }
                this.dialogVisible = true
            },
            beforeAvatarUpload(file) {
                const isVideo = new Set([
                    'video/mp4',
                    'video/avi',
                    'video/3pg',
                    'video/wmv',
                    'video/rmvb'
                ]).has(file.type)
                const isLt50M = file.size / 1024 / 1024 < 50
                if (!isVideo) {
                    this.$message.error('视频格式仅支持mp4、avi、3gp、wmv、rmwb格式!')
                }
                if (!isLt50M) {
                    this.$message.error('上传视频大小不能超过 50MB!')
                }
                return isVideo && isLt50M
            },
            handleAvatarSuccess: function (res, file, fileList) {
                if (res.code === 0) {
                    this.changeImgTag()
                    // this.videoFlag = false;
                    this.eventUploadPercent=0
                    this.uploadDisabled = true
                    this.filename = res.url
                    this.$notify({
                        title: '成功',
                        message: '上传成功',
                        type: 'success',
                        duration: 2000
                    })
                    console.log("upload succ.");
                } else {
                    this.videoFlag = false;
                    this.eventUploadPercent=0
                    fileList.pop();
                    this.uploadDisabled = false
                    Message({
                        message: res.msg,
                        type: 'error',
                        duration: 5 * 1000
                    })
                }
            },
            handleAvatarError(err, file, fileList) {
                fileList.pop();
                this.videoFlag = false;
                this.eventUploadPercent=0
                this.uploadDisabled = false
            },
            handleProgress(event, file, fileList) {
                this.uploadDisabled = true;
                this.videoFlag = true;
                let percent = Math.floor(event.percent)
                if(percent<99){
                    this.eventUploadPercent=percent
                }
                if(percent===100){
                    this.eventUploadPercent=99
                }
            },
            changeImgTag() {
                let imgTag = document.querySelectorAll('li img.el-upload-list__item-thumbnail')
                if (imgTag && imgTag.length > 0) {
                    console.log('检测到应为video的img标签', imgTag)
                    for (let i = 0; i < imgTag.length; i++) {
                        let currentImgTag = imgTag[i]
                        let currentImgTagSrc = currentImgTag.getAttribute('src')
                        let srcSubStr = currentImgTagSrc.substring(currentImgTagSrc.lastIndexOf('.') + 1, currentImgTagSrc.length)
                        let isVideo = new Set(['mp4', 'avi', '3pg', 'wmv', 'rmvb']).has(srcSubStr)
                        if (isVideo) {
                            let parentNode = currentImgTag.parentNode
                            let newElement = document.createElement('video')
                            newElement.setAttribute('class', currentImgTag.getAttribute('class'))
                            newElement.setAttribute('src', currentImgTagSrc)
                            parentNode.replaceChild(newElement, currentImgTag)
                        }
                    }

                }
            }
        },
        mounted() {
            this.$nextTick(function () {
                this.changeImgTag()
            })
        },
        created: function () {
            if (this.fileList.length > 0) {
                if (this.fileList[0]['url'] != '' && this.fileList[0]['url'] != null) {
                    this.uploadDisabled = true
                    this.filename = this.fileList[0]['url']
                } else {
                    this.fileList = []
                }
            }
        }
    }
</script>

<style scoped>
    .disabled >>> .el-upload--picture-card {
        display: none;
    }
    /deep/ .el-upload-list--picture-card .el-progress {
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
        bottom: auto;
        width: 126px;
        content-visibility: hidden;
    }
</style>
